//
//  HMComposeView.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/21.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//
//
import UIKit
import pop

class HMComposeView: UIView {

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)//========><======
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var buttonArray: [HMComposeButton] = [HMComposeButton]()
    
    // 显示视图
    func show(fromVC: UIViewController?) {
        //将当前的视图添加到window上/根视图控制器的view上/传递控制器
        fromVC?.view.addSubview(self)
        
        for (index, btn) in buttonArray.enumerated() {
            
            startAnimation(btn: btn, index: index)
        }
    }
    
    // 开始动画  isShow: Bool = true 这是一个套路
    private func startAnimation(btn: HMComposeButton,index: Int, isShow: Bool = true) {
        
        // 实例化弹性动画对象
        let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        // 设置属性
        springAnimation?.springSpeed = 10
        springAnimation?.springBounciness = 10.0
        
        // 设置延迟时间
        springAnimation?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        
        let btnCenterY = btn.center.y + CGFloat(isShow ? -350 : 350)
        springAnimation?.toValue = NSValue.init(cgPoint: CGPoint(x: btn.center.x, y: btnCenterY))
        btn.pop_add(springAnimation, forKey: nil)
    }
    
    
    // 创建背景视图
    private lazy var backView: UIImageView = UIImageView(image: UIImage.snapShortCurrentWindow().applyDarkEffect())
    
    // 创建logo视图
    private lazy var logoView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "compose_slogan"))
    
    private func setupUI() {
        
//        let toolBar = UIToolbar(frame: UIScreen.main.bounds)
//        toolBar.barStyle = .black
        
        addSubview(backView)
        addSubview(logoView)
        
        logoView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addComposeButton()
    }
    
    // 添加按钮
    private func addComposeButton() {
        
        let btnMargin = (ScreenWidth - 3 * composeBtnWidth) / 4
        
        for i in 0 ..< 6 {
            let btn = HMComposeButton()
            
            
            let col = i % 3
            let row = i / 3
            
            let btnX = btnMargin + (composeBtnWidth + btnMargin) * CGFloat(col)
            let btnY = ScreenHeight + (composeBtnHeight + btnMargin) * CGFloat(row)
            
            btn.setImage(#imageLiteral(resourceName: "tabbar_compose_idea"), for: .normal)
            btn.setTitle("点我", for: .normal)
            btn.frame = CGRect(x: btnX, y: btnY, width: composeBtnWidth, height: composeBtnHeight)
            
            addSubview(btn)
            
            // 数组中添加按钮
            buttonArray.append(btn)
            
            btn.addTarget(self, action: #selector(clickComposeButton(btn:)), for: .touchUpInside)
        }
    }
    
    @objc private func clickComposeButton(btn: HMComposeButton) {
    //1.被点击的按钮执行放大 其他按钮执行缩小   -> 修改transform
        UIView.animate(withDuration: 0.5, animations: {
            
            for composeBtn in self.buttonArray {
                if composeBtn == btn {
                    composeBtn.transform = CGAffineTransform.init(scaleX: 2, y: 2)
                } else {
                    composeBtn.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2)
                    composeBtn.alpha = 0.1
                }
            }
        }, completion: { (_) -> () in
            //2.跳转对应的控制器
            //通过网络数据已经解析了一个控制器名称的字符串   这是swift和OC的一个不同之处,直接手写也可以
            let bundleName = Bundle.main.infoDictionary?["CFBundleName"] as! String
            let className = bundleName + "." + "HMComposeViewController"
            
            // UIViewController.Type  和 UIViewController.self 的区别
            guard let classType = NSClassFromString(className) as? UIViewController.Type else {
                return
            }
            let vc = classType.init()
            
            let nav = UINavigationController(rootViewController: vc)
            
            //present 和 dismiss 并不是马上就完成
            UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: { 
                //但是 跳转完控制器之后希望立即执行一些操作的时候
                self.removeFromSuperview()
            })
            
        })
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        // 相反的
        for (index,btn) in buttonArray.reversed().enumerated() {
            
            startAnimation(btn: btn, index: index, isShow: false)
        }
        
        // 动画执行完后移除视图  必须延迟移除不然很丑很别扭
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
            self.removeFromSuperview()
        })
    }
}

